#include "cdc_acm_core.h"
#include "usbd_hw.h"
#include "lwrb.h"

#define USB_DATASEND_MAXSIZE        1024
#define USB_DATAREV_MAXSIZE         1024

#define     USB_SINGALSEND_MAXSIZE  1024                 //USB单次发送的最大字节数
usb_dev usbd_cdc;

uint8_t usb_revbuff[USB_DATAREV_MAXSIZE];               //USB数据接收缓冲队列使用的数组
uint8_t usb_sendbuff[USB_DATASEND_MAXSIZE];             //USB数据发送缓冲队列使用的数组

lwrb_t usbrev_ringbuff;                                 //USB数据接收缓冲队列
lwrb_t usbsend_ringbuff;                                //USB数据发送缓冲队列

uint8_t usb_senddata[USB_SINGALSEND_MAXSIZE];

uint8_t data[ USB_DATAREV_MAXSIZE];
/*!
    \brief      main routine
    \param[in]  none
    \param[out] none
    \retval     none
*/
int main(void)
{
    uint16_t size = 0;
    uint8_t send_num = 0;

    /*初始化队列，同于存放发送和接收队列*/
    lwrb_init(&usbrev_ringbuff, usb_revbuff, USB_DATAREV_MAXSIZE);
    lwrb_init(&usbsend_ringbuff, usb_sendbuff, USB_DATASEND_MAXSIZE);

    /* system clocks configuration */
    rcu_config();

    /* GPIO configuration */
    gpio_config();

    /* USB device configuration */
    usbd_init(&usbd_cdc, &cdc_desc, &cdc_class);

    /* NVIC configuration */
    nvic_config();

    /* enabled USB pull-up */
    usbd_connect(&usbd_cdc);

    while (1) {
        //USB被打开
        if(USBD_CONFIGURED == usbd_cdc.cur_status)
        {
            //数据接收后转发
            size = lwrb_get_full(&usbrev_ringbuff);
            if(size != 0)
            {
                lwrb_read(&usbrev_ringbuff, data, size);
                lwrb_write(&usbsend_ringbuff,data,size);
            }

            /*检查是否有发送缓冲队列中是否有数据*/
            size = lwrb_get_full(&usbsend_ringbuff);
            if (size != 0)
            {
                /*检查是否可以发送数据*/
                if ( (USBD_CONFIGURED == usbd_cdc.cur_status) && (0U == cdc_acm_check_send(&usbd_cdc)))
                {
                    //从缓存队列中读出数据
                    lwrb_read(&usbsend_ringbuff, usb_senddata, size);
                    //USB发送数据
                    cdc_acm_data_send (&usbd_cdc, usb_senddata, size);
                }
            }

            /*检查USB是否在空闲状态*/
            if (0U == cdc_acm_check_ready(&usbd_cdc))
            {
                /*可以从新接收数据*/
                cdc_acm_data_receive(&usbd_cdc);
            }
        }

    }
}
